#include <iostream>
#include <vector>
// OS
#include <pthread.h>
#include <unistd.h>

std::string ToHex(int num)
{
	char buffer[64] = {0};
	snprintf(buffer, sizeof(buffer), "0x%d", num);
	return buffer;
}

//int gval = 5; //多线程共享
__thread int gval = 5;//多线程各自有独立的gval，// 只在Linux有效， __thread只能修饰内置类型

void *ThreadRun(void *args)
{
	std::cout << "new thread running..., tid:" << ToHex(pthread_self()) << ", gval:" << gval-- << ", &gval:" << &gval << std::endl;
	return args;
}
class ThreadData
{
public:
	char name[64];
};
int main()
{
	std::vector<pthread_t> tids;   // 存放多线程的tid
	std::vector<ThreadData *> tds; // 方便统一释放
	// 多线程创建
	for (int i = 1; i <= 5; i++)
	{
		pthread_t tid; // 线程属性集合的虚拟起始地址，在pthread中维护
		ThreadData *td = new ThreadData;
		snprintf(td->name, sizeof(td->name), "thread-%d", i);
		int n = pthread_create(&tid, nullptr, ThreadRun, (void *)td);
		if (n != 0) // 出错返回错误码
		{
			perror("pthread fail");
		}
		tids.push_back(tid);
		tds.push_back(td);
		sleep(1);
	}

	// 等待
	for (auto e : tids)
	{
		void *result = nullptr;
		int n = pthread_join(e, &result);
		if (n != 0) // 出错返回错误码
		{
			perror("pthread_join fail");
		}
		std::cout << "wait " << ((ThreadData *)result)->name << " success" << std::endl;
		sleep(1);
	}

	return 0;
}
